import 'package:get/get.dart';

import '../../../common/api/x_cms_assemble_control.dart';
import '../../../common/models/cms/cms_category_data.dart';
import '../../../common/utils/event_bus.dart';
import '../../../common/utils/loading.dart';
import '../../../common/utils/log_util.dart';
import '../../../common/utils/o2_utils.dart';
import '../../common/create_form/view.dart';
import 'cms_document/view.dart';

class CmsHelper {


  //私有构造函数
  CmsHelper._internal();

  //保存单例
  static final CmsHelper _singleton =
      CmsHelper._internal();

  //工厂构造函数
  factory CmsHelper() => _singleton;

  final _eventBus = EventBus();

  /// 创建文档
  Future<void> startCreateDocument(CmsCategoryData category,  {Map<String, dynamic>? cmsMessageData}) async {
    if (  category.id == null || category.appId == null) {
      Loading.toast('cms_create_document_no_args'.tr);
      return;
    }
    Loading.show();
    final app = await CmsAssembleControlService.to.getApp(category.appId!);
    Loading.dismiss();
    if (app == null) {
      Loading.toast('cms_app_error'.tr);
      return;
    }

    final config = app.config ?? '{}';
    final configMap = O2Utils.parseStringToJson(config);
    final messageData = cmsMessageData ?? {};
    bool ignoreTitle = false; // 是否忽略标题
    bool latest = true; // 是否查询草稿
    if (messageData.containsKey('ignoreTitle')) {
      ignoreTitle = messageData['ignoreTitle'] ?? false;
    } else if (configMap.containsKey('ignoreTitle')) {
      ignoreTitle = configMap['ignoreTitle'] ?? false;
    }
    if (messageData.containsKey('latest')) {
      latest = messageData['latest'] ?? true;
    } else if (configMap.containsKey('latest')) {
      latest = configMap['latest'] ?? true;
    }
    if (latest) {
      var drafts =
          await CmsAssembleControlService.to.listDocumentDraft(category.id!);
      if (drafts != null && drafts.isNotEmpty) {
        OLogger.d('创建文档，当前用户有草稿。。。。');
        await CmsDocumentPage.open(drafts[0].id!,
            title: drafts[0].title ?? '', options: {"readonly": false});
        _eventBus.emit(EventBus.cmsCategoryDocListRefreshMsg);
        return;
      }
    }

    await CreateFormPage.startCmsDoc(ignoreTitle, category: category, cmsData: messageData['data']);
    _eventBus.emit(EventBus.cmsCategoryDocListRefreshMsg);
  }
}